<?php

namespace App\Model;
use Hyperf\Database\Model\SoftDeletes;
use function Hyperf\Config\config;

class Administrator extends Model
{
    use SoftDeletes;

    // 封禁的用户状态
    const FORBID_STATUS = 0;

    // 正常用户的状态
    const NORMAL_STATUS = 1;
    protected ?string $table = 'administrators';
    /**
     * NOTE:可批量赋值的属性。
     * @var array
     */
    protected array $fillable = ['name', 'password', 'email', 'mobile', 'gender', 'avatar', 'introduction', 'status', 'login_at'];
    /**
     * NOTE:隐藏字段
     * @var array|string[]
     */
    protected array $hidden = ['password', 'deleted_at', 'created_at', 'updated_at'];

    /**
     * Notes:根据id获取用户信息
     * 2025/7/9
     * @param $key
     * @return Administrator|Administrator[]|\Hyperf\Database\Model\Collection|\Hyperf\Database\Model\Model|null
     */
    public static function retrieveById($key)
    {
        return (new self())->find($key);
    }

    /**
     * Notes:获取 id
     * 2025/7/9
     * @return \Hyperf\Tappable\HigherOrderTapProxy|mixed|null
     */
    public function getId()
    {
        // TODO: Implement getId() method.
        return $this->id;
    }

    public function roles()
    {
        return  $this->belongsToMany(\App\Model\Role::class, 'administrator_role', 'administrator_id', 'role_id');
    }

    /**
     * 获取用户的菜单列表.
     */
    public function menus(): array
    {
        $menuList = [];
        foreach ($this->roles()->get() as $role) {
            // 获取用户所属角色的菜单权限
            $menus = $role->menus()->orderBy('sort')->get();
            foreach ($menus as $menu) {
                if (! in_array($menu->id, $menuList)) {
                    $menuList[$menu->id] = $menu->toArray();
                }
            }
        }
        return array_values($menuList);
    }

    /**
     * 判断用户是否有某个路由的权限.
     */
    public function hasPermission(string $controller, string $action, string $method): bool
    {
        $roles = $this->roles()->get();
        foreach ($roles as $role) {
            if ($role->role_key === config('permission.admin_role_key', 'admin')) {
                return true;
            }
        }
        // 查找当前路由的权限
        $currentPermission = \App\Model\Permission::query()->where('controller', $controller)
            ->where('action', $action)
            ->where('http_method', $method)
            ->first();
        if (! $currentPermission) {
            // 如果当前的路由没有设置权限， 则通过
            return true;
        }

        $hasPermission = false;
        foreach ($roles as $role) {
            $permissions = $role->permissions()->get();
            foreach ($permissions as $permission) {
                if ($permission->id == $currentPermission->id) {
                    $hasPermission = true;
                    break;
                }
            }
        }

        return $hasPermission;
    }
}